/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.faare.persistence;

import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.persistence.javabeans.JBTop;
import opiam.admin.faare.service.UserContext;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * Lazy loading for attributes corresponding to mapped objects.
 */
public class LazyJBTopCollection extends LazyStringCollection
{
    /** Instance of logger. */
    private static Logger _logger = Logger.getLogger(LazyJBTopCollection.class);

    /** List of loaded elements. */
    private Map loaded;

    /**
     * Creates a new LazyJBTopCollection object.
     *
     * @param enclosing Dname of entry containing attribute to load.
     * @param atts Attribute to load.
     * @param auserContext Connected user context.
     */
    public LazyJBTopCollection(String enclosing, ArrayList atts,
        UserContext auserContext)
    {
        super(enclosing, atts, auserContext);
        loaded = new HashMap();

        _logger.debug("constructeur enclosing : " + enclosing);
        _logger.debug("constructeur userContext : " + auserContext);
    }

    /**
     * @see java.util.Collection#add(Object).
     */
    @Override
	public boolean add(Object o)
    {
        super.add(o);

        return (loaded.put(((JBTop) o).getDn(), o) != o);
    }

    /**
     * @see java.util.Collection#iterator().
     */
    @Override
	public Iterator iterator()
    {
        return new LazyJBTopIterator(this);
    }

    /**
     * Loads element corresponding to given dname.
     *
     * @param dn Dname.
     * @param auserContext User context.
     *
     * @return Loaded element.
     */
    protected Object lazyLoadObj(Object dn, UserContext auserContext)
    {
        _logger.debug("lazyLoad dn : " + dn);

        Object o;

        try
        {
            o = PersistenceLDAP.load((String) dn, auserContext);
            loaded.put(dn, o);

            return o;
        }
        catch (Exception e)
        {
            _logger.error(MessageUtil.formatMessage(
                    "MSG_LDAP_ERROR_NO_SUCH_OBJECT", dn));

            return null;
        }
    }

    /**
     * Gets list of loaded elements.
     * @return map of elements.
     */
    protected Map getLoaded()
    {
        return loaded;
    }
}
